#include "wjsruntime.h"

WJsRuntime::WJsRuntime()
{
    //ctor
    _runtime = nullptr ;
    _ctx = nullptr ;
}

static JSContext *JS_NewCustomContext(JSRuntime *rt)
{
  JSContext *ctx =   JS_NewContextRaw(rt);
  if (!ctx){
    printf("JS_NewContext failed.\n");
    return NULL;
  }

    JS_AddIntrinsicBaseObjects(ctx);
    JS_AddIntrinsicDate(ctx);
    //JS_AddIntrinsicEval(ctx);// add others just core dump, i donot know why. no much time to study. 2024/1/25.
    //JS_AddIntrinsicStringNormalize(ctx);
    //JS_AddIntrinsicRegExp(ctx);
    //JS_AddIntrinsicJSON(ctx);
    //JS_AddIntrinsicProxy(ctx);
    //JS_AddIntrinsicMapSet(ctx);
    //JS_AddIntrinsicTypedArrays(ctx);
    //JS_AddIntrinsicPromise(ctx);
  return ctx;
}


bool WJsRuntime::init(size_t memlimitMB, string& error)
{
    if( _runtime!=nullptr ){
        error = "_runtime is already inited." ;
        return false ;
    }
    _runtime = JS_NewRuntime();
    if (!_runtime)
    {
        error = "JS_NewRuntime failed." ;
        return false ;
    }

    if( memlimitMB>0 ) {
        JS_SetMemoryLimit(_runtime, memlimitMB*1024*1024 );
    }


    js_std_set_worker_new_context_func(JS_NewCustomContext);
    js_std_init_handlers(_runtime);
    _ctx = JS_NewCustomContext(_runtime);
    //_ctx = JS_NewContext(_runtime);
    if (!_ctx)
    {
        error = "JS_NewContext failed." ;
        return false ;
    }
    char* targv[] = {""} ;
    js_std_add_helpers(_ctx, 0, targv);
    //JS_AddIntrinsicBaseObjects(  _ctx );
    //JS_AddIntrinsicDate(_ctx);
    JS_AddIntrinsicEval(_ctx) ;
    //JS_AddIntrinsicStringNormalize(_ctx);
    JS_AddIntrinsicJSON(_ctx);


    JS_SetMemoryLimit (_runtime, 1024 * 1024); //1MB
    JS_SetMaxStackSize(_runtime, 10 * 1024);

    return true ;
}


WJsRuntime::~WJsRuntime()
{
    //dtor
    if( _ctx != nullptr ) {
        JS_FreeContext(_ctx) ;
        _ctx = nullptr ;
    }
    if( _runtime!=nullptr ) {
        JS_FreeRuntime(_runtime) ;
        _runtime = nullptr ;
    }
}

void WJsRuntime::dump_error()
{
    if( _ctx ) {
        js_std_dump_error(_ctx) ;
    }

}
